<template>
	<view>
		<view class="container">
			<view class="contact">
				<view class="map_icon">
					<u-icon name="map" size="34rpx"></u-icon>
				</view>

				<view class="contact_item" @tap="goToAddr" v-if="addressInfo.id">
					<view class="contact_right">
						<view>
							<text>{{addressInfo.contact_name}}</text>
							<text style="margin-left: 20rpx">{{addressInfo.contact_phone}}</text>
						</view>
						<u-icon name="arrow-right" size="30rpx" ></u-icon>
					</view>
					<view class="addr">
						收货地址：{{addressInfo.province}}-{{addressInfo.city}}-{{addressInfo.district}}-{{addressInfo.address}}
					</view>
				</view>
				<view class="contact_item" @tap="goToAddr" v-else>
					<view class="contact_right">
						<view>
							<!-- <text>{{addressInfo.contact_name}}</text>
							<text style="margin-left: 20rpx">{{addressInfo.contact_phone}}</text> -->
							选择收货地址
						</view>
						<u-icon name="arrow-right" size="30rpx" ></u-icon>
					</view>
					<view class="addr">
						<!-- 收货地址：{{addressInfo.province}}-{{addressInfo.city}}-{{addressInfo.district}}-{{addressInfo.address}} -->
					</view>
				</view>
			</view>
			<view class="goods" style="padding-bottom: 10rpx">
				<block v-if="type == 'product'" v-for="(item, index) in order" :key="index">
					<view class="center">
						<view class="goods_img">
							<image :src="'https://images.weserv.nl/?url=' + item.image[0]" mode=""></image>
						</view>
						<view class="goods_info">
							<view>
								{{ item.title }}
							</view>
							<view style="font-size: 22rpx;">
								规格：{{ skuItem.title }}
							</view>
							<view class="price_num">
								<view class="price">￥{{ skuItem.price }}</view>
								<view class="num">x{{ item.num }}</view>
							</view>
						</view>
					</view>
				</block>
				<block v-if="type == 'cart'" v-for="(item, index) in order" :key="index">
					<view class="center">
						<view class="goods_img">
							<image :src="'https://images.weserv.nl/?url=' + item.product_sku.product.image[0]" mode=""></image>
						</view>
						<view class="goods_info">
							<view>
								{{ item.product_sku.product.title }}
							</view>
							<view style="font-size: 22rpx;">
								规格：{{ item.product_sku.title }}
							</view>
							<view class="price_num">
								<view class="price">￥{{ item.product_sku.price }}</view>
								<view class="num">x{{ item.amount }}</view>
							</view>
						</view>
					</view>
				</block>
				<u-line></u-line>
				<view class="remark">
					<u-row>
						<u-col span="4">
							<view v-if="productInfo.is_remark == 0">买家留言</view>
							<view v-else>* 买家留言</view>
						</u-col>
						<u-col span="8">
							<u-input
								:border="false"
								placeholder="留言前建议先与商家协调一致"
								fontSize="24rpx"
								inputAlign="right"
								v-model="remark"
							></u-input>
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="goods" style="padding: 10rpx 30rpx;">
				<!-- <view class="remark"> -->
					<u-row>
						<u-col span="3">
							<view>优惠券</view>
						</u-col>
						<u-col span="9">
							<u-input
								:border="false"
								placeholder="请输入优惠券码"
								fontSize="24rpx"
								inputAlign="right"
								v-model="coupons"
								style="padding: 0;"
							></u-input>
						</u-col>
					</u-row>
				<!-- </view> -->
			</view>
			<view class="goods">
				<u-row>
					<u-col span="3">
						<view>商品金额</view>
					</u-col>
					<u-col span="9">
						<view style="text-align: right; font-weight: bold">
							￥{{totalAmount}}
						</view>
					</u-col>
				</u-row>
			</view>
		</view>

		<view class="bottom_tab">
			<view class="right_total">
				<view>
				<!-- 	共
					<text class="num">12</text>
					件 -->
				</view>
				<view class="total_text">总计:</view>
				<view class="total_price">
					<text class="priceText">￥{{totalAmount}}</text>
				</view>
			</view>
			<view>
				<!-- @click="submitOrder" -->
				<u-button @click="openDiologClick" text="提交订单"></u-button>
			</view>
		</view>
		<cc-downloadDialog :show="show" :peanNum="20" :type="1" word="立即支付" :money="money"
		@close="closeDiologClick" @pay='submitOrder'></cc-downloadDialog>
	</view>
</template>

<script>
import { productsInfo } from '@/api/base.js'
import { cartList } from '@/api/shopcart.js'
import { addressList } from '@/api/address.js'
import { createOrder , wechatpay , coupons } from '@/api/order.js'
export default {
	data() {
		return {
			btnStyle: {
				height: '32rpx'
			},
			order: [], //订单列表
			type:'',//商品下单/购物车下单
			addressInfo:{},//收货地址
			remark:'', // 留言
			itemList:[], //生成订单的商品列表参数
			// totalAmount:0
			show: false,
			coupons:'',//优惠券码
			money:'',
			skuItem:{},
			productInfo:{}
		};
	},
	onShow() {
		addressList().then(res => {
			if(res.data.length > 0){
				this.addressInfo = res.data[0]
			}else{
				uni.showToast({
					title:'请添加收货地址',
					icon:'error',
					duration:2000
				})
			}
		})
	},
	onLoad(options) {
		this.type = options.type
		if(options.type == 'product'){
			productsInfo(options.id).then(res => {
				if(res.status == 200){
					const list = res.data
					list.num = options.num
					this.order.push(list)
					this.skuItem = list.skus.filter(i => i.id == options.skuId)[0]
					this.productInfo = list
				}
				console.log('选中规格内容',this.skuItem)
				
				this.itemList = [
					{
						sku_id:this.skuItem.id,
						amount:this.order[0].num
					}
				]
				console.log('最终productInfo',this.productInfo)
			})
			
		}else if(options.type == 'cart'){
			cartList().then(res => {
				if(res.status == 200){
					this.order = []
					const list1 = JSON.parse(options.ids)
					const list2 = res.data
					list2.forEach(a => {
						list1.forEach(b => {
							if(a.id === b.id){
								a.amount = b.amount
								this.order.push(a)
							}
						})
					})
					this.productInfo = this.order[0].product_sku.product
					this.order.forEach(item => {
						this.itemList.push({sku_id:item.product_sku.id,amount:item.amount})
						if(item.product_sku.product.is_remark == 1){
							this.productInfo = item.product_sku.product
						}
					})
					console.log('最终productInfo',this.productInfo)
					
				}
			})
			
		}
		
		
		 // 监听来自 navigateBack 的事件
		    uni.$on('onBack', (data) => {
				if(data){
					this.addressInfo = data
				}
			  
		    });
	},
	computed:{
		// 总额
		 totalAmount() {
			 if (this.type === 'product') {
			     return this.order.reduce((total, order) => {
			       return total + (order.num * this.skuItem.price);
			     }, 0).toFixed(2); // 使用 toFixed(2) 来保留两位小数
			   } else if (this.type === 'cart') {
			     return this.order.reduce((total, order) => {
			       return total + (order.amount * order.product_sku.price);
			     }, 0).toFixed(2); // 使用 toFixed(2) 来保留两位小数
			   }
		    
		  }
	},
	methods: {
		// 打开弹框
        openDiologClick() {
			if(this.addressInfo.id){
				if(this.coupons != ''){
					coupons(this.coupons).then(res => {
						if(res.status == 200){
							if(res.data.type == 'fixed'){
								if(Number(this.totalAmount) >= Number(res.data.min_amount)){
									if(this.productInfo.is_remark == 1){
										if(this.remark == ''){
											uni.showToast({
												title:'请填写买家留言',
												icon:'error',
												duration:2000
											})
										}else{
											this.money = (Number(this.totalAmount) - Number(res.data.value)).toFixed(2)
											this.show = true;
										}
									}else{
										this.money = (Number(this.totalAmount) - Number(res.data.value)).toFixed(2)
										this.show = true;
									}
									
								}else{
									if(this.productInfo.is_remark == 1){
										if(this.remark == ''){
											uni.showToast({
												title:'请填写买家留言',
												icon:'error',
												duration:2000
											})
										}else{
											this.money = this.totalAmount
											this.show = true;
										}
									}else{
										this.money = this.totalAmount
										this.show = true;
									}
									
								}
							}else if(res.data.type == 'percent'){
								if(Number(this.totalAmount) >= Number(res.data.min_amount)){
									if(this.productInfo.is_remark == 1){
										if(this.remark == ''){
											uni.showToast({
												title:'请填写买家留言',
												icon:'error',
												duration:2000
											})
										}else{
											this.money = (Number(this.totalAmount) - Number(this.totalAmount) * Number(res.data.value)/100).toFixed(2)
											this.show = true;
										}
									}else{
										this.money = (Number(this.totalAmount) - Number(this.totalAmount) * Number(res.data.value)/100).toFixed(2)
										this.show = true;
									}
									
								}else{
									if(this.productInfo.is_remark == 1){
										if(this.remark == ''){
											uni.showToast({
												title:'请填写买家留言',
												icon:'error',
												duration:2000
											})
										}else{
											this.money = this.totalAmount
											this.show = true;
										}
									}else{
										this.money = this.totalAmount
										this.show = true;
									}
									
								}
							}
							
						}
					})
				}else{
					if(this.productInfo.is_remark == 1){
						if(this.remark == ''){
							uni.showToast({
								title:'请填写买家留言',
								icon:'error',
								duration:2000
							})
						}else{
							this.money = this.totalAmount
							this.show = true;
						}
					}else{
						this.money = this.totalAmount
						this.show = true;
					}
					
				}
			}else{
				uni.showToast({
					title:'请选择收货地址',
					icon:'error',
					duration:2000
				})
			}
			
			
            
        },
		// 关闭弹框
        closeDiologClick() {
            this.show = false;
        },
		goToAddr(){
			uni.navigateTo({
				url:'/userPage/addrPath/addrPathList?lastPage=order'
			})
		},
		// 提交订单
		submitOrder(){
			const list = {
				address_id:this.addressInfo.id,
				remark:this.remark,
				items:this.itemList,
				coupon_code:this.coupons
			}
			createOrder(list).then(res => {
				wechatpay(res.data.id).then(r => {
					if(r.status == 200){
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: r.data.orderInfo.timeStamp,
							nonceStr: r.data.orderInfo.nonceStr,
							package: r.data.orderInfo.package,
							signType:r.data.orderInfo.signType,
							paySign: r.data.orderInfo.paySign,
							success: function (res) {
								// 处理支付成功的逻辑
								uni.redirectTo({
									url:'/orderPage/payresults/payresults?isPay=true'
								})
							},
							fail: function (err) {
								console.error('支付失败:', err);
								// 处理支付失败的逻辑
								// payResults
								uni.redirectTo({
									url:'/orderPage/payresults/payresults?isPay=false'
								})
							}
						});
					}
				})
			})
			
			
		},
	}
};
</script>

<style lang="scss" scoped>
	.content {
	        display: flex;
	        flex-direction: column;
	
	    }
.bottom_tab {
	position: fixed;
	bottom: 0;
	height: 100rpx;
	width: 750rpx;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	background-color: #fff;

	& .right_total {
		display: flex;
		font-size: 28rpx;

		line-height: 36rpx;
		.num {
			color: #77818e;
		}
		& .total_text {
			width: 84rpx;
			font-weight: 400;
			color: #0a0b0c;
			margin-left: 20rpx;
		}
		& .total_price {
			display: flex;
			justify-content: space-between;
			flex-direction: column;
			align-items: center;
			& .priceText {
				font-weight: 600;
				color: #1786f8;
			}
			& .total_free {
				padding-top: 12rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #77818e;
				line-height: 32rpx;
			}
		}
	}
	& /deep/ .u-button {
		width: 180rpx;
		height: 80rpx;
		font-size: 28rpx;
		line-height: 80rpx;
		margin-left: 24rpx;
		background-color: #1786f8;
		color: #ffffff;
		text-align: center;
		border-radius: 40rpx;
		margin-right: 30rpx;
	}
}
.container {
	padding: 30rpx;
	.goods {
		border-radius: 10rpx;
		background-color: #fff;
		// height: 120rpx;
		margin-top: 30rpx;
		padding: 30rpx;
		font-size: 27rpx;
		.center {
			font-size: 30rpx;
			display: flex;
			margin-bottom: 30rpx;
			.goods_img {
				margin-right: 30rpx;
				image {
					width: 140rpx;
					height: 140rpx;
					border-radius: 10rpx;
				}
			}
			.goods_info {
				display: flex;
				justify-content: space-between;
				flex-direction: column;
				flex: 1;
				.price_num {
					display: flex;
					justify-content: space-between;
					.price {
						font-weight: bold;
						color: #1786f8;
					}
					.num {
						color: #777;
					}
				}
			}
		}
	}
	.contact {
		border-radius: 10rpx;
		background-color: #fff;
		padding: 30rpx;
		position: relative;
		font-size: 30rpx;
		.map_icon{
			height: 40rpx;
			line-height: 40rpx;
			position: absolute;
			display: flex;
			align-items: center;
		}
		.contact_item {
			margin-left: 50rpx;
			font-size: 28rpx;
			.contact_right {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 40rpx;
				line-height: 40rpx;
			}
			.addr{
				margin-right: 50rpx;
				margin-top: 10rpx;
			}
		}
	}
}
</style>
